﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using RabbitMQ.Client;

namespace WorkStation.Frameworks.EasyBus.MessageQueue.RabbitMq
{
    /// <summary>
    /// RabbitMq 终结点实现
    /// </summary>
    public class RabbitMqEndpoint : EndpointBase
    {
        private ConnectionFactory _factory = null;

        public string HostName { get; set; }
        public string VirtualHost { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public int Port { get; set; }
        public string QueueName { get; set; }

        public static readonly string EXCHANGE_NAME = "EasyBus.In";

        public ConnectionFactory RabbitMqFactory 
        {
            get 
            {
                Interlocked.CompareExchange<ConnectionFactory>(
                    ref this._factory,
                    new ConnectionFactory()
                    {
                        UserName = this.UserName,
                        HostName = this.HostName,
                        VirtualHost = this.VirtualHost,
                        Password = this.Password,
                        Port = this.Port
                    },
                    null);

                return this._factory;
            }
        }

        public override IChannel GetChannel()
        {
            return new RabbitMqChannel(this);
        }

        public override bool EndpointEqualsCore(object obj)
        {
            RabbitMqEndpoint other = obj as RabbitMqEndpoint;

            if (other.HostName.Equals(other.HostName) && other.Port == other.Port && other.QueueName.Equals(this.QueueName) && other.VirtualHost.Equals(this.VirtualHost))
            {
                return true;
            }
            else 
            {
                return false;
            }
        }
    }
}
